package com.example.ecommerce.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ecommerce.common.exception.BusinessException;
import com.example.ecommerce.dto.ProductDTO;
import com.example.ecommerce.dto.ProductSpecDTO;
import com.example.ecommerce.entity.Product;
import com.example.ecommerce.entity.ProductCategory;
import com.example.ecommerce.mapper.ProductMapper;
import com.example.ecommerce.service.ProductCategoryService;
import com.example.ecommerce.service.ProductService;
import com.example.ecommerce.service.ProductSpecService;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    
    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private ProductSpecService productSpecService;
    
    @Autowired
    private ProductCategoryService categoryService;
    
    @Autowired
    private ModelMapper modelMapper;

    @Override
    public ProductDTO getProductById(Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        ProductDTO productDTO = modelMapper.map(product, ProductDTO.class);
        
        // 设置分类名称
        ProductCategory category = categoryService.getById(product.getCategoryId());
        if (category != null) {
            productDTO.setCategoryName(category.getName());
        }
        
        // 设置规格信息
        List<ProductSpecDTO> specs = productSpecService.getSpecsByProductId(id);
        productDTO.setSpecs(specs);
        
        return productDTO;
    }

    @Override
    public Page<ProductDTO> getProductList(Integer page, Integer size, Long categoryId, String keyword) {
        Page<Product> productPage = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        
        if (categoryId != null) {
            queryWrapper.eq(Product::getCategoryId, categoryId);
        }
        
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(Product::getName, keyword)
                    .or()
                    .like(Product::getDescription, keyword);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Product::getCreatedAt);
        
        // 执行分页查询
        Page<Product> result = productMapper.selectPage(productPage, queryWrapper);
        
        // 转换为DTO
        List<ProductDTO> productDTOs = result.getRecords().stream()
                .map(product -> {
                    ProductDTO dto = modelMapper.map(product, ProductDTO.class);
                    // 设置分类名称
                    ProductCategory category = categoryService.getById(product.getCategoryId());
                    if (category != null) {
                        dto.setCategoryName(category.getName());
                    }
                    // 设置规格信息
                    List<ProductSpecDTO> specs = productSpecService.getSpecsByProductId(product.getId());
                    dto.setSpecs(specs);
                    return dto;
                })
                .collect(Collectors.toList());
        
        Page<ProductDTO> dtoPage = new Page<>(result.getCurrent(), result.getSize(), result.getTotal());
        dtoPage.setRecords(productDTOs);
        
        return dtoPage;
    }

    @Override
    public ProductDTO createProduct(ProductDTO productDTO) {
        // 验证分类是否存在
        if (!categoryService.exists(productDTO.getCategoryId())) {
            throw new BusinessException("商品分类不存在");
        }
        
        // 转换为实体并保存
        Product product = modelMapper.map(productDTO, Product.class);
        product.setCreatedAt(LocalDateTime.now());
        productMapper.insert(product);
        
        // 保存规格信息
        if (productDTO.getSpecs() != null) {
            productDTO.getSpecs().forEach(spec -> {
                spec.setProductId(product.getId());
                productSpecService.createSpec(spec);
            });
        }
        
        return getProductById(product.getId());
    }

    @Override
    public ProductDTO updateProduct(Long id, ProductDTO productDTO) {
        Product existingProduct = productMapper.selectById(id);
        if (existingProduct == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 验证分类是否存在
        if (!categoryService.exists(productDTO.getCategoryId())) {
            throw new BusinessException("商品分类不存在");
        }
        
        // 更新商品基本信息
        Product product = modelMapper.map(productDTO, Product.class);
        product.setId(id);
        productMapper.updateById(product);
        
        // 更新规格信息
        if (productDTO.getSpecs() != null) {
            // 删除原有规格
            productSpecService.deleteByProductId(id);
            // 添加新规格
            productDTO.getSpecs().forEach(spec -> {
                spec.setProductId(id);
                productSpecService.createSpec(spec);
            });
        }
        
        return getProductById(id);
    }

    @Override
    public void deleteProduct(Long id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 删除商品规格
        productSpecService.deleteByProductId(id);
        
        // 删除商品
        productMapper.deleteById(id);
    }

    @Override
    public void updateStock(Long id, Integer stock) {
        if (stock < 0) {
            throw new BusinessException("库存不能小于0");
        }
        
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        Product updateProduct = new Product();
        updateProduct.setId(id);
        updateProduct.setStock(stock);
        productMapper.updateById(updateProduct);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        if (status != 0 && status != 1) {
            throw new BusinessException("状态值无效");
        }
        
        Product product = productMapper.selectById(id);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        Product updateProduct = new Product();
        updateProduct.setId(id);
        updateProduct.setStatus(status);
        productMapper.updateById(updateProduct);
    }

    @Override
    public boolean exists(Long id) {
        return getById(id) != null;
    }
} 